package com.wzd.learn.springboot.persistence.mongo.impl;

import java.io.InputStream;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.FindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.wzd.learn.springboot.persistence.entity.mongo.ImageFile;
import com.wzd.learn.springboot.persistence.mongo.MongoDao;
import com.wzd.learn.springboot.persistence.mongo.TestDao;

@Component
public class TestDaoImpl extends MongoDao implements TestDao {
	protected static final String COLLECTION = "test";

	@Override
	public void query() {
		FindIterable<Document> resutList = mongoTemplate.getCollection(
				COLLECTION).find();
		System.out.println(JSON.toJSONString(resutList.first()));
	}
	
	@Override
	public void saveBJson(ImageFile file) {
		mongoTemplate.insert(file, "image");
	}

	/**
	 * 存储文件
	 */
	@Override
	public ObjectId SaveFile(InputStream content, String filename) {
		try {
			return gridFsTemplate.store(content, filename);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("存储文件时发生错误！！！");
		}
		return null;
	}

	/**
	 * 取出文件
	 */
	@Override
	public InputStream retrieveFileOne(String filename) {
		try {
			GridFSFile file = gridFsTemplate.findOne(new Query()
					.addCriteria(Criteria.where("filename").is(filename)));
			return gridFsTemplate.getResource(file).getInputStream();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
}
